<template>
  <div class="modal-page">
    <el-dialog
      v-model="DialogVisible"
      :title="title"
      width="30%"
      center
      destroy-on-close
    >
      <div>
        <FhForm v-bind="modalConfig" v-model="formData"></FhForm>
        <slot></slot>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handlerOkClick">确定</el-button>
          <el-button @click="DialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import { useStore } from '@/store'

import FhForm from '@/base-ui/form'

export default defineComponent({
  components: {
    FhForm
  },
  props: {
    title: {
      type: String,
      required: true
    },
    modalConfig: {
      type: Object,
      required: true
    },
    defaultInfo: {
      type: Object,
      default: () => ({})
    },
    // 对modal的menu-tree的扩展
    otherInfo: {
      type: Object,
      default: () => ({})
    },
    pageName: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const DialogVisible = ref(false)

    const formData = ref<any>({})
    // watch的第一个参数为 一个getter函数或者ref或者reactivy
    watch(
      () => props.defaultInfo,
      (newValue: any) => {
        for (const item of props.modalConfig.formItems) {
          formData.value[`${item.field}`] = newValue[`${item.field}`]
        }
      }
    )
    // 点击确认按钮的逻辑
    const store = useStore()
    const handlerOkClick = () => {
      console.log('编辑')
      DialogVisible.value = false
      if (Object.keys(props.defaultInfo).length) {
        store.dispatch('system/editPageDataAction', {
          pageName: props.pageName,
          editData: { ...formData.value, ...props.otherInfo },
          id: props.defaultInfo.id
        })
      } else {
        console.log('新建')
        store.dispatch('system/createPageDataAction', {
          pageName: props.pageName,
          newData: { ...formData.value, ...props.otherInfo }
        })
      }
    }

    return {
      DialogVisible,
      formData,
      handlerOkClick
    }
  }
})
</script>

<style scoped></style>
